package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeEditPasswordDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordEditFailedException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();


        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //判断redis中是否含有当前用户名locak的对象
        String key=username+"locak";
        Object o = redisTemplate.opsForValue().get(key);
        if(o!=null){
            throw new PasswordErrorException(MessageConstant.ACCOUNT_LOCKED);
        }

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 进行MD5密码加密DigestUtils.md5DigestAsHex这个工具类的方法进行密码加密
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(employee.getPassword())) {
            //密码错误
            //向redis中插入数据
            redisTemplate.opsForValue().set(username+System.currentTimeMillis(),"err",5, TimeUnit.MINUTES);
            String prefix =username+ "*";
            Set keys = redisTemplate.keys(prefix);
            //锁定该账号
            if(keys.size()>=5){
                redisTemplate.opsForValue().set(key,"locaked",1,TimeUnit.HOURS);

            }
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     * @param employeeDTO
     */
    @Override
    public void addEmployee(EmployeeDTO employeeDTO) {
        /*封装员工对象，使用BeanUtils简化代码*/
        Employee employee=new Employee();
        BeanUtils.copyProperties(employeeDTO,employee);
        /*补全数据库中的字段*/
        //设置创建时间
        employee.setCreateTime(LocalDateTime.now());

        //设置员工状态
        employee.setStatus(StatusConstant.ENABLE);

        //设置更新时间
        employee.setUpdateTime(LocalDateTime.now());

        /*设置默认密码并进行MD5加密*/
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置创建人和修改人
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.addEmployee(employee);
    }

    /**
     * 员工分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult queryByPage(EmployeePageQueryDTO employeePageQueryDTO) {
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        Page<Employee> page=employeeMapper.queryByPage(employeePageQueryDTO);
        long total=page.getTotal();
        List<Employee> records=page.getResult();
        return new PageResult(total,records);
    }

    /**
     * 员工账号启停
     * @param status
     * @param id
     */
    @Override
    public void enableAccout(Integer status,long id) {
        employeeMapper.enableAccount(status,id);
    }

    /**
     *修改员工信息
     * @param employeeDTO
     */
    @Override
    public void editEmpInfo(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //进行数据拷贝，将传输对象的属性值拷贝到员工类中的属性
        BeanUtils.copyProperties(employeeDTO,employee);
        //更新数据库中的字段
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());
        employeeMapper.editEmpInfo(employee);
    }

    /**
     * 根据id进行查询员工信息
     * @param id
     */
    @Override
    public Employee queryById(long id) {
        Employee employee=employeeMapper.queryById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 修改员工密码
     * @param employeeEditPasswordDTO
     */
    @Override
    public void editPassword(EmployeeEditPasswordDTO employeeEditPasswordDTO) {
        if(employeeEditPasswordDTO.getOldPassword().equals(employeeEditPasswordDTO.getNewPassword())){
            throw new PasswordEditFailedException(MessageConstant.OLD_AND_NEW_PASSWORDS_ARE_THE_SAME);
        }else {
            Long empId=BaseContext.getCurrentId();
            String newPassword=DigestUtils.md5DigestAsHex(employeeEditPasswordDTO.getNewPassword().getBytes());
            employeeMapper.editPassword(empId,newPassword);
        }
    }

}
